<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
		
		<el-form-item label="体测评分标准" prop="jcsjXmid" label-width="100">
			<el-select filterable v-model="queryParams.jcsjjXmflid" @change="handleQuery" placeholder="选择评分标准" clearable>
				<el-option
				  v-for="d in tctypeList"
				  :key="d.id"
				  :label="d.xmflTitle"
				  :value="d.id"
				/>
			</el-select>
		</el-form-item>
		<el-form-item label="体测项目" prop="jcsjXmid">
			<el-select filterable v-model="queryParams.jcsjXmid" @change="handleQuery" placeholder="选择体测项目" clearable>
				<el-option
				  v-for="d in projectList"
				  :key="d.id"
				  :label="d.xmMc"
				  :value="d.id"
				/>
			</el-select>
		</el-form-item>
<!-- 		


      <el-form-item label="状态" prop="jcsjStatus">
        <el-select v-model="queryParams.jcsjStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in tc_qyzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
	  -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tc:jcsj:add']"
        >新增</el-button>
      </el-col>
	  <!-- 
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tc:jcsj:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tc:jcsj:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tc:jcsj:export']"
        >导出</el-button>
      </el-col>
	  
	   -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  :show-overflow-tooltip="true" v-loading="loading" :data="jcsjList" @selection-change="handleSelectionChange">
		<!-- <el-table-column type="selection" width="55" align="center" /> -->
		<el-table-column type="index" label="序号" width="55" align="center" />
		<el-table-column label="项目分类" align="center" prop="jcsjjXmflid" >
			<template #default="scope">
				<span  v-for="c in tctypeList"
				  :key="c.id"
				  :label="c.xmflTitle"
				  :value="c.id"
				>{{scope.row.jcsjjXmflid==c.id?c.xmflTitle:''}}</span>
			</template>
		</el-table-column>
		<el-table-column label="体测项目" align="center" prop="jcsjXmid" >
			<template #default="scope">
				<span  v-for="c in projectList"
				  :key="c.id"
				  :label="c.xmMc"
				  :value="c.id"
				>{{scope.row.jcsjXmid==c.id?c.xmMc:''}}</span>
			</template>
		</el-table-column>
		<el-table-column label="详细规则" align="center" prop="jcsjGz">
			<template #default="scope">
				{{(scope.row.jcsjGz!=null && scope.row.jcsjGz!='{}')?'已添写规则':'没有规则'}}
			</template>
		</el-table-column>
<!-- 	  
      <el-table-column label="状态" align="center" prop="jcsjStatus">
        <template #default="scope">
          <dict-tag :options="tc_qyzt" :value="scope.row.jcsjStatus"/>
        </template>
      </el-table-column>
	  -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleLook(scope.row)" v-hasPermi="['tc:jcsj:query']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasRole="['admin', 'common']" v-hasPermi="['tc:jcsj:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasRole="['admin', 'common']" v-hasPermi="['tc:jcsj:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改体测项目基础数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="jcsjRef" :model="form" :rules="rules" label-width="120px">
		
		
		<el-form-item label="体测评分标准" prop="jcsjjXmflid">
			<el-select filterable v-model="form.jcsjjXmflid" @change="selectType" placeholder="体测评分标准" :disabled="auform">
				<el-option
				  v-for="d in tctypeList"
				  :key="d.id"
				  :label="d.xmflTitle"
				  :value="d.id"
				/>
			</el-select>
		</el-form-item>
		<el-form-item label="体测项目" prop="jcsjXmid">
			<el-select filterable v-model="form.jcsjXmid" placeholder="体测项目" :disabled="auform">
				<el-option
				  v-for="d in projectList_tmp"
				  :key="d.id"
				  :label="d.xmMc"
				  :value="d.id"
				/>
			</el-select>
		</el-form-item>
		  
        <el-form-item label="规则" prop="jcsjGz"  v-if="!auform">
          <el-input v-model="form.jcsjGz" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
		
		<el-form-item label="性别" v-if="auform">
		  <el-select v-model="sex" @change="sexChange" placeholder="性别" :disabled="false">
		    <el-option
		      v-for="dict in sys_user_sex"
		      :key="dict.value"
		      :label="dict.label"
		      :value="dict.value"
		    />
		  </el-select>
		</el-form-item>
		<el-form-item label="年级"  v-if="auform">
		  <el-select v-model="gzTableNJ" @change="njChange" placeholder="请选择年级" :disabled="false">
		    <el-option
		      v-for="dict in tc_nj"
		      :key="dict.value"
		      :label="dict.label"
		      :value="dict.value"
		    />
		  </el-select>
		</el-form-item>
		
		  <el-table :data="gzTable" style="width: 100%"  max-height="350"  v-if="auform">
			<el-table-column prop="level" label="级别" />
			<el-table-column prop="fs" label="分数" />
			<el-table-column prop="start_d" label="数据标准" >
				<template #default="scope">
					{{scope.row.start_d == 0?scope.row.end_d:scope.row.start_d}} {{unit}}
				</template>
			</el-table-column>		
		  </el-table>

		
<!-- 		
        <el-form-item label="创建时间" prop="jcsjCreate">
          <el-date-picker clearable
            v-model="form.jcsjCreate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建者" prop="jcsjCreateby">
          <el-input v-model="form.jcsjCreateby" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="状态" prop="jcsjStatus">
          <el-radio-group v-model="form.jcsjStatus">
            <el-radio
              v-for="dict in tc_qyzt"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新时间" prop="jcsjUpdate">
          <el-date-picker clearable
            v-model="form.jcsjUpdate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新者" prop="jcsjUpdateby">
          <el-input v-model="form.jcsjUpdateby" placeholder="请输入更新者" />
        </el-form-item>
		
		 -->
		
      </el-form>
      <template #footer  v-if="auform == false">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Jcsj">
import { listJcsj, getJcsj, delJcsj, addJcsj, updateJcsj } from "@/api/tc/jcsj";
import { listTctype,getTctype} from "@/api/tc/tctype";
import { listProject} from "@/api/tc/project";

const { proxy } = getCurrentInstance();
const { tc_qyzt,tc_nj,sys_user_sex } = proxy.useDict('tc_qyzt','tc_nj','sys_user_sex');

const jcsjList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const projectList = ref([]);
const projectList_tmp = ref([]);
const tctypeList = ref([]);
const auform=ref(true);
const gzTable=ref([]);
const gzTableNJ=ref();
const sex=ref("");
const A=ref([]); //男
const B=ref([]); //女
const unit=ref([]); //单位
const tmpProPar={pageNum: 1,pageSize: 999,xmStatus:'1'};


const tmpGetPar=ref({"pageNum": 1,"pageSize": 500,"bjXxid" : '-1'});


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    jcsjXmid: null,
    jcsjjXmflid: null,
    jcsjGz: null,
    jcsjStatus: null,
  },
  rules: {
	  jcsjXmid: [
	    { required: true, message: "评分标准不能为空", trigger: "change" }
	  ],
	  jcsjjXmflid: [
	    { required: true, message: "体测项目不能为空", trigger: "change" }
	  ],
	  jcsjGz: [
	    { required: true, message: "体测规则不能为空", trigger: "blur" }
	  ],
	  jcsjStatus: [
	    { required: true, message: "体测规则不能为空", trigger: "blur" }
	  ]
  }
});

const { queryParams, form, rules } = toRefs(data);

 onMounted(() => {
      // console.log('组件已经挂载')
	// getDeptInfo();  
	// getProjectList();
	getList();
	getTcTypeList();
	
 })
 /** 查询评分标准列表 */
 function getTcTypeList() {
   loading.value = true;
   tmpGetPar.xmflStatus='1';
   listTctype(tmpGetPar).then(response => {
     tctypeList.value = response.rows;
     loading.value = false;
 	 getProjectList();
   });
 }
 /** 查询体测项目列表 */
 function getProjectList() {
   loading.value = true;
   listProject(tmpProPar).then(response => {
	   // console.log(response.rows)
     projectList.value = response.rows;
     loading.value = false;
   });
 }

/** 查询体测项目基础数据列表 */
function getList() {
  loading.value = true;
  listJcsj(queryParams.value).then(response => {
    jcsjList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    jcsjXmid: null,
    jcsjjXmflid: tctypeList.value[0].id,
    jcsjGz: null,
    jcsjCreate: null,
    jcsjCreateby: null,
    jcsjStatus: null,
    jcsjUpdate: null,
    jcsjUpdateby: null
  };
  proxy.resetForm("jcsjRef");
  selectType(tctypeList.value[0].id);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ID);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function selectType(id){
	// console.log(id)
	projectList_tmp.value=[];
	form.value.jcsjXmid=null;
	getTctype(id).then(response => {
	  // console.log(response.data)
	  // projectList_tmp
	  for(let d of response.data.tcProjectTpList){
		  for(let d2 of  projectList.value){
			  if(d2.id == d.projectid){
				  projectList_tmp.value.push(d2);
				  break;
			  }
		  }
	  }
	  
	  // projectList_tmp.value=  projectList.value.filter(function(currentValue,index,arr){
	  // 	// console.log(currentValue)
	  // 	return currentValue.xxid == e ;
	  // });
	});
}

/** 新增按钮操作 */
function handleAdd() {
  auform.value=false;
  reset();
  open.value = true;
  title.value = "添加体测项目基础数据";
  
}

/** 修改按钮操作 */
function handleUpdate(row) {
  auform.value=false;
  reset();
  const _id = row.id || ids.value
  getJcsj(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改体测项目基础数据";
  });
}
/** 查看按钮操作 */
function handleLook(row) {
  auform.value=true;
  reset();
  const _id = row.id || ids.value
  getJcsj(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看体测项目基础数据";
	getTableToGZJson(form.value.jcsjGz)
	gzTable.value=[];
	gzTableNJ.value=null;
	sex.value='0';
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["jcsjRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateJcsj(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addJcsj(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _IDs = row.id || ids.value;
  let tmp=tctypeList.value.filter(function(currentValue,index,arr){
		// console.log(currentValue)
		return currentValue.id == row.jcsjjXmflid ;
	});
	console.log(_IDs)
  proxy.$modal.confirm('是否确认删除 "' + tmp[0].xmflTitle +'" 的数据项？').then(function() {
    return delJcsj(_IDs);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tc/jcsj/export', {
    ...queryParams.value
  }, `jcsj_${new Date().getTime()}.xlsx`)
}

function getTableToGZJson(d){
	let json=JSON.parse(d);
	unit.value=json["data"]["unit"];
	A.value=json["data"]["A"];
	B.value=json["data"]["B"];
	
}
function njChange(e){
	try{
		gzTableNJ.value=e;
		if(sex.value==0){
			gzTable.value=A.value["gz"+gzTableNJ.value];
		}else if(sex.value==1){
			gzTable.value=B.value["gz"+gzTableNJ.value];
		}else{
			gzTable.value=[];
		}
	}catch(e){
		gzTable.value=[];
	}
	// for (let key in A.value) {
	// 	// let nj=key.substring(2,key.length);
		
	// 	// console.log(nj+"年级");
	// 	gzTableNJ.value=e;
	// 	gzTable.value=A[key];
	// 	// for (let key2 in A[key]) {
	// 	// 	console.log(A[key][key2]);
	// 	// 	// gzTable.value=A[key][key2];
	// 	// }
	//   // console.log(key + ": " + A[key]);
	//   // console.log(A[key]);
	// }
}

function sexChange(e){
	sex.value=e;
	try{
		if(sex.value==0){
			gzTable.value=A.value["gz"+gzTableNJ.value];
		}else if(sex.value==1){
			gzTable.value=B.value["gz"+gzTableNJ.value];
		}else{
			gzTable.value=[];
		}
	}catch(e){
		gzTable.value=[];
	}
}
</script>
